package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

// java example
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 当执行插入语句时, @TableField(fill = FieldFill.INSERT)
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        setFieldValByName("createBy", getLoginUserId(), metaObject);
        setFieldValByName("createTime", new Date(), metaObject);
        setFieldValByName("updateTime", new Date(), metaObject);
    }

    // 当执行更新语句时, @TableField(fill = FieldFill.UPDATE)
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        setFieldValByName("updateBy", getLoginUserId(), metaObject);
        setFieldValByName("updateTime", new Date(), metaObject);
    }

    /**
     * 获取登录用户的id, TODO 完成登录功能后
     * @return
     */
    public String getLoginUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();

            if (loginUser != null) {
                return loginUser.getUserId().toString();
            }
        } catch (Exception e) {
            //throw new RuntimeException(e);
        }
        return "1";
    }
}